package com.dobby.pea.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dobby.pea.common.R;
import com.dobby.pea.entity.tbUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import com.dobby.pea.service.UserService;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author Dobby
 * @version 1.0
 */

@RestController
@RequestMapping("/api/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 返回所有用户信息
     * @return
     */
    @GetMapping("/all")
    public R<List<tbUser>> allUser(){
        LambdaQueryWrapper<tbUser> queryWrapper = new LambdaQueryWrapper<>();
        List<tbUser> list = userService.list(queryWrapper);
        return R.success(list);
    }


    /**
     * 新增用户
     * @param tbUser
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody tbUser tbUser){
        log.info("新增用户，用户信息：{}",tbUser.toString());
        tbUser.setPassword(DigestUtils.md5DigestAsHex(tbUser.getPassword().getBytes()));
        userService.save(tbUser);
        return R.success("新增员工成功");
    }

    /**
     * 用户登录
     * @param request
     * @param user
     * @return
     */
    @PostMapping("/login")
    public R<tbUser> login(HttpServletRequest request, HttpServletResponse response, @RequestBody tbUser user){

        //将页面提交的密码password进行md5加密处理
        String password = user.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        LambdaQueryWrapper<tbUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(tbUser::getUsername,user.getUsername());
        tbUser tbUser = userService.getOne(queryWrapper);

        //是否查询到
        if(tbUser == null){
            return R.error("账号未注册");
        }

        //密码比对
        if(!tbUser.getPassword().equals(password)){
            return R.error("账号密码错误");
        }

        //员工状态
        if(tbUser.getStatus() == 0){
            return R.error("账号已禁用");
        }

        //登录成功，保存id至cookie
        Cookie cookie = new Cookie("userId",String.valueOf(tbUser.getId()));
        cookie.setHttpOnly(true);
        cookie.setPath("/");
        response.addCookie(cookie);

        return R.success(tbUser);
    }


    /**
     * 用户退出登录
     * 移除前端session中的user
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request, HttpServletResponse response){
        //删除cookie的userId字段
        Cookie[] cks = request.getCookies();
        if (cks != null) {
            for (Cookie ck : cks) {
                if (StringUtils.equals(ck.getName(), "userId")) {
                    ck.setPath("/");
                    ck.setMaxAge(0); // maxAge设置成0，代表删除cookie
                    response.addCookie(ck);
                }
            }
        }
        return R.success("退出成功");
    }


    /**
     * 用户分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name){
        log.info("page = {},pageSize = {},name = {}" ,page,pageSize,name);

        //构造分页构造器
        Page pageInfo = new Page(page,pageSize);

        //构造条件构造器
        LambdaQueryWrapper<tbUser> queryWrapper = new LambdaQueryWrapper();
        //添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name),tbUser::getUsername,name);
        //添加排序条件
        queryWrapper.orderByDesc(tbUser::getUpdateTime);

        //执行查询
        userService.page(pageInfo,queryWrapper);

        return R.success(pageInfo);
    }


    /**
     * 用户更新
     * @param request
     * @param user
     * @return
     */
    @PutMapping
    public R<String> update(HttpServletRequest request,@RequestBody tbUser user){
        log.info(user.toString());
        userService.updateById(user);
        return R.success("员工信息修改成功");
    }

    /**
     * 根据id查询用户信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<tbUser> getById(@PathVariable Long id){
        log.info("根据id查询员工信息...");
        tbUser user = userService.getById(id);
        if(user != null){
            return R.success(user);
        }
        return R.error("没有查询到对应员工信息");
    }



}
